
package com.feib.soeasy.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.MenuItem;
import com.feib.soeasy.model.UserActionLog;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.MenuItemService;
import com.feib.soeasy.service.UserActionLogService;
import com.feib.soeasy.util.UserUtil;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.LocalizableMessage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.DateTypeConverter;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;


/**
 * @title (#)Soez9006ActionBean.java<br>
 * @description 交易日誌查詢 Controller<br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2011/1/13 create by Jimmy Liu<br>
 */
public class Soez9006ActionBean extends BaseActionBean {

    private static final String DEFAULT_JSP = "/WEB-INF/views/soez9006/soez9006.jsp";
    
    /**
     * 業者代號查詢畫面
     */
    private static final String AJAX_QUERY_GROUP_JSP = "/WEB-INF/views/soez9006/groupPopUpList.jsp";
    
    /**
     * 查詢條件
     */
    private UserActionLog qryUserActionLog;
    
    /**
     * 查詢條件-交易日期起
     */
    @Validate( required=true, on={"doQuery"}, converter=DateTypeConverter.class)
    private Date qryInDateFrom;
    
    /**
     * 查詢條件-交易時間起
     */
    private Integer qryInDateHourFrom;
    
    /**
     * 查詢條件-交易日期迄
     */
    @Validate( required=true, on={"doQuery"}, converter=DateTypeConverter.class)
    private Date qryInDateTo;
    
    /**
     * 查詢條件-交易時間迄
     */
    private Integer qryInDateHourTo;

    /**
     * 查詢結果
     */
    private PaginatedList<UserActionLog> queryResult;

    /**
     * 帳單業者查詢條件
     */
    private Group qryGroup;

    /**
     * 帳單業者查詢結果
     */
    private PaginatedList<Group> queryGroupResult;
    
    @SpringBean("userActionLogService")
    private UserActionLogService userActionLogService;
    
    @SpringBean("groupService")
    private GroupService groupService;

    /**
     * 所有的程式清單
     */
    private Map<MenuItem, Set<MenuItem>> menuItems;

    @SpringBean("menuItemService")
    private MenuItemService menuItemService;
    
    /**
     * 鈎選的子程式清單
     */
    private String qryActionBeans;

    
    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        qryInDateFrom = new Date();
        qryInDateTo = new Date();
        qryInDateHourFrom = new Integer(0);
        qryInDateHourTo = new Integer(24);

        //如果不是銀行端，則查詢條件要加入帳單業者限制
        if (!UserUtil.isBankGroup())
        {
            qryUserActionLog = new UserActionLog();
            qryUserActionLog.setGroupNo(UserUtil.getUserGroup().getGroupNo());
        }
        /*
         * 若非銀行端，且畫面未勾取任何條件，則需要加入限制條件
         */
        Iterator<MenuItem> menusIt = this.getMenuItems().keySet().iterator();
        while(menusIt.hasNext())
        {
            MenuItem menu = menusIt.next();
            menu.setChecked(Boolean.TRUE);
            Set<MenuItem> subMenus = this.getMenuItems().get(menu);
            
            for(MenuItem subMenu : subMenus)
            {
                subMenu.setChecked(Boolean.TRUE);
            }
        }
        
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 查詢
     * @return
     */
    public Resolution doQuery()
    {
        logger.debug("Enter doQuery mehtod.");
        try {

            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == this.qryUserActionLog)
                qryUserActionLog = new UserActionLog();


            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                qryUserActionLog.setGroupPk(UserUtil.getUserGroup().getGroupPk());
            }
            

            // 上傳時間查詢條件設定
            if (null != qryInDateFrom)
            {                
                Calendar cal = Calendar.getInstance();
                cal.setTime(qryInDateFrom);
                if (24 > qryInDateHourFrom.intValue())
                    cal.set(Calendar.HOUR_OF_DAY, qryInDateHourFrom.intValue());
                else
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);
                qryInDateFrom = cal.getTime();
            }

            if (null != qryInDateHourTo)
            {
                // 將時分秒設定在23:59:59
                
                Calendar cal = Calendar.getInstance();
                cal.setTime(qryInDateTo);
                if (24 > qryInDateHourTo.intValue())
                    cal.set(Calendar.HOUR_OF_DAY, qryInDateHourTo.intValue());
                else
                    cal.set(Calendar.HOUR_OF_DAY, 23);
                cal.set(Calendar.MINUTE, 59);
                cal.set(Calendar.SECOND, 59);
                qryInDateTo = cal.getTime();
            }
            
            List<String> actionBeans = new ArrayList<String>();            
            if (null != qryActionBeans)
            {
                String[] abs = qryActionBeans.split(",");
                for(String actionBean: abs)
                {
                    if (null != actionBean)
                    {
                        actionBeans.add(actionBean);
                    }
                }
            }
                        

            if (actionBeans.isEmpty())
            {
                // 無選取，則查無資料
                if (null == queryResult)
                    queryResult = new PaginatedList<UserActionLog>();
                queryResult.setFullListSize(0);
            }
            else
            {
                //呼叫服務查詢
                if (null == queryResult)
                    queryResult = new PaginatedList<UserActionLog>();
                queryResult = userActionLogService.queryByUserActionLog(qryUserActionLog, qryInDateFrom, qryInDateTo, actionBeans, queryResult);
                
                
                /* 方便下次次查詢 */
                Iterator<MenuItem> menusIt = this.getMenuItems().keySet().iterator();
                while(menusIt.hasNext())
                {
                    MenuItem menu = menusIt.next();
                    Set<MenuItem> subMenus = this.getMenuItems().get(menu);
                    
                    for(MenuItem subMenu : subMenus)
                    {
                        for(String actionBean: actionBeans)
                        {
                            if (actionBean.equals(subMenu.getActionBean()))
                            {
                                subMenu.setChecked(Boolean.TRUE);
                                actionBeans.remove(actionBean);
                                break;
                            }
                        }
                    }
                }
                
                /* */
                menusIt = this.getMenuItems().keySet().iterator();
                while(menusIt.hasNext())
                {
                    MenuItem menu = menusIt.next();
                    Set<MenuItem> subMenus = this.getMenuItems().get(menu);
                    
                    boolean allCheked = true;
                    for(MenuItem subMenu : subMenus)
                        allCheked = allCheked && (null == subMenu.getChecked() ? false : subMenu.getChecked().booleanValue());
                    
                    menu.setChecked(new Boolean(allCheked));
                }
            }
            
        }
        catch (Exception e) {
            logger.error("", e);
        }
        return new ForwardResolution(DEFAULT_JSP); 
    }

    /**
     * 帳單業者查詢
     * @return
     */
    public Resolution doAjaxQueryGroups()
    {
        logger.debug("Enter doAjaxQueryGroups mehtod.");
        try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                throw new Exception(new LocalizableMessage("no.authority").getMessage(getContext().getLocale()));
            }


            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryGroup)
                qryGroup = new Group();

            //呼叫服務查詢
            queryGroupResult = groupService.queryByGroup(qryGroup, queryGroupResult);
        }
        catch (Exception e) {
            logger.error("交易日誌查詢-帳單業者查詢錯誤(Soez9006ActionBean.doAjaxQueryGroups):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new SimpleError("查詢錯誤！"));
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_GROUP_JSP);
    }

    
    /**
     * @return the qryUserActionLog
     */
    public UserActionLog getQryUserActionLog() {
        return qryUserActionLog;
    }

    
    /**
     * @param qryUserActionLog the qryUserActionLog to set
     */
    public void setQryUserActionLog(UserActionLog qryUserActionLog) {
        this.qryUserActionLog = qryUserActionLog;
    }


    
    /**
     * @return the qryInDateFrom
     */
    public Date getQryInDateFrom() {
        return qryInDateFrom;
    }


    
    /**
     * @param qryInDateFrom the qryInDateFrom to set
     */
    public void setQryInDateFrom(Date qryInDateFrom) {
        this.qryInDateFrom = qryInDateFrom;
    }


    
    /**
     * @return the qryInDateTo
     */
    public Date getQryInDateTo() {
        return qryInDateTo;
    }


    
    /**
     * @param qryInDateTo the qryInDateTo to set
     */
    public void setQryInDateTo(Date qryInDateTo) {
        this.qryInDateTo = qryInDateTo;
    }


    
    /**
     * @return the qryInDateHourFrom
     */
    public Integer getQryInDateHourFrom() {
        return qryInDateHourFrom;
    }


    
    /**
     * @param qryInDateHourFrom the qryInDateHourFrom to set
     */
    public void setQryInDateHourFrom(Integer qryInDateHourFrom) {
        this.qryInDateHourFrom = qryInDateHourFrom;
    }


    
    /**
     * @return the qryInDateHourTo
     */
    public Integer getQryInDateHourTo() {
        return qryInDateHourTo;
    }


    
    /**
     * @param qryInDateHourTo the qryInDateHourTo to set
     */
    public void setQryInDateHourTo(Integer qryInDateHourTo) {
        this.qryInDateHourTo = qryInDateHourTo;
    }


    
    /**
     * @return the qryGroup
     */
    public Group getQryGroup() {
        return qryGroup;
    }


    
    /**
     * @param qryGroup the qryGroup to set
     */
    public void setQryGroup(Group qryGroup) {
        this.qryGroup = qryGroup;
    }

    
    /**
     * @return the queryGroupResult
     */
    public PaginatedList<Group> getQueryGroupResult() {
        return queryGroupResult;
    }

    
    /**
     * @param queryGroupResult the queryGroupResult to set
     */
    public void setQueryGroupResult(PaginatedList<Group> queryGroupResult) {
        this.queryGroupResult = queryGroupResult;
    }

    
    /**
     * @return the queryResult
     */
    public PaginatedList<UserActionLog> getQueryResult() {
        return queryResult;
    }

    

    /**
     * @param queryResult the queryResult to set
     */
    public void setQueryResult(PaginatedList<UserActionLog> queryResult) {
        this.queryResult = queryResult;
    }

    
    /**
     * @return the menuItems
     */
    public Map<MenuItem, Set<MenuItem>> getMenuItems() {
        if (null == menuItems)
        {
            menuItems = new TreeMap<MenuItem, Set<MenuItem>>(new Comparator<MenuItem>() {
                @Override
                public int compare(MenuItem o1, MenuItem o2) {
                    int o1No = (null == o1.getOrderNo() ? -1 : o1.getOrderNo().intValue());
                    int o2No = (null == o2.getOrderNo() ? -1 : o2.getOrderNo().intValue());
                    if (o1No == o2No)
                        return 0;
                    else if (o1No > o2No)
                        return 1;
                    else return -1;
                }
            });
            
            Iterator<MenuItem> it = menuItemService.queryAllLazyRoles().iterator();
            while( it.hasNext())
            {
                MenuItem menuItem = (MenuItem) it.next();
                if (null != menuItem.getParentMenuItem() && (null != menuItem.getParentMenuItem().getEnabled() &&  menuItem.getParentMenuItem().getEnabled().booleanValue()) )
                {
                    // 子選單
                    Set<MenuItem> subMenuItems = menuItems.get(menuItem.getParentMenuItem());
                    if (null == subMenuItems)
                    {
                        subMenuItems = new TreeSet<MenuItem>(new Comparator<MenuItem>(){
                            @Override
                            public int compare(MenuItem o1, MenuItem o2) {
                                int o1No = (null == o1.getOrderNo() ? -1 : o1.getOrderNo().intValue());
                                int o2No = (null == o2.getOrderNo() ? -1 : o2.getOrderNo().intValue());
                                if (o1No == o2No)
                                    return 0;
                                else if (o1No > o2No)
                                    return 1;
                                else return -1;
                            }}
                        );                            
                        menuItems.put(menuItem.getParentMenuItem(), subMenuItems);
                    }
                    

                    
                    /* 2011/04/18 需過慮群組類別 */
                    if (!UserUtil.isBankGroup())
                    {
                        if (UserUtil.isSchoolGroup())
                        {
                            if (null == menuItem.getSchool() || ! menuItem.getSchool().booleanValue())
                                continue;
                        }
                        else
                        {
                            if (null == menuItem.getCommittee() || ! menuItem.getCommittee().booleanValue())
                                continue;
                        }
                        
                    }
                    
                    if (!subMenuItems.contains(menuItem))
                        subMenuItems.add(menuItem);
                }
                else
                {
                    // 主選單 或是，do nothing.
                    // 若是都沒有子選單，也不需要顯示主選單                       
                }
            }
        }
        return menuItems;
    }

    
    /**
     * @return the qryActionBeans
     */
    public String getQryActionBeans() {
        return qryActionBeans;
    }

    
    /**
     * @param qryActionBeans the qryActionBeans to set
     */
    public void setQryActionBeans(String qryActionBeans) {
        this.qryActionBeans = qryActionBeans;
    }


}
